package kxfang.com.user.acitvity.set;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;

import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;

import com.hjq.permissions.OnPermission;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.listener.OnResultCallbackListener;
import com.orhanobut.hawk.Hawk;
import com.orhanobut.logger.Logger;

import java.util.ArrayList;
import java.util.List;

import kxfang.com.base.activity.MvvmBaseActivity;
import kxfang.com.base.utils.GsonUtils;
import kxfang.com.base.viewmodel.IMvvmBaseViewModel;
import kxfang.com.common.bean.AppUser;
import kxfang.com.common.config.HttpConfig;
import kxfang.com.common.constant.Constant;
import kxfang.com.common.dialog.MenuDialog;
import kxfang.com.common.parameter.LoginPar;
import kxfang.com.common.router.RoutHub;
import kxfang.com.common.utils.DataCleanManager;
import kxfang.com.common.utils.DataHelputils;
import kxfang.com.common.utils.GlideEngine;
import kxfang.com.common.utils.HawkUtil;
import kxfang.com.common.utils.MyUtils;
import kxfang.com.common.utils.RouterUtils;
import kxfang.com.common.utils.SelectImageUtil;
import kxfang.com.common.utils.StatusBarUtil;
import kxfang.com.common.views.BaseDialog;
import kxfang.com.http.EasyHttp;
import kxfang.com.http.callback.SimpleCallBack;
import kxfang.com.http.exception.ApiException;
import kxfang.com.user.R;
import kxfang.com.user.databinding.UserActivityEditInformationBinding;


/**
 * 个人资料页面
 */
public class EditInformationActivity extends MvvmBaseActivity<UserActivityEditInformationBinding, IMvvmBaseViewModel> {

    private static final int REQUEST_CODE = 0x00000011;
    private String url = "";


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        StatusBarUtil.setTopActivityView(this, viewDataBinding.topView);
        DataHelputils.name = "0";
        initView();
    }

    @Override
    protected IMvvmBaseViewModel getViewModel() {
        return null;
    }

    @Override
    protected int getBindingVariable() {
        return 0;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.user_activity_edit_information;
    }

    @Override
    protected void onRetryBtnClick() {

    }

    private void initView() {
        viewDataBinding.activityBack.setOnClickListener(view -> finish());
        viewDataBinding.nichengText.setText(Hawk.get("alias"));
        viewDataBinding.phoneText.setText(Hawk.get("phone"));
        if (Hawk.get("head") != null && !TextUtils.isEmpty(Hawk.get("head"))) {
            url = Hawk.get("head");
            Glide.with(this).load(url).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(viewDataBinding.headImage);
        } else {
            Glide.with(this).load(R.drawable.default_head).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(viewDataBinding.headImage);
        }
        Intent intent = new Intent();
        viewDataBinding.settingPwd.setOnClickListener(v -> {
//            intent.setClass(this, UpdatePasswordActivity.class);
//            startActivity(intent);
        });
        viewDataBinding.headImage.setOnClickListener(v -> {
            XXPermissions.with(EditInformationActivity.this)
                    .constantRequest() //可设置被拒绝后继续申请，直到用户授权或者永久拒绝
                    .permission(Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE) //支持请求6.0悬浮窗权限8.0请求安装权限
                    .request(new OnPermission() {

                        @Override
                        public void hasPermission(List<String> granted, boolean isAll) {
                            if (isAll) {
                                Logger.d("获取权限成功");
                            } else {
                                Logger.d("获取权限成功，部分权限未正常授予");
                            }

                        }

                        @Override
                        public void noPermission(List<String> denied, boolean quick) {
                            if (quick) {
                                ToastUtils.showShort("被永久拒绝授权，请手动权限");
                            } else {
                                ToastUtils.showShort("权限失败");
                            }
                        }
                    });
            popuShare();
        });
        viewDataBinding.nichengLayout.setOnClickListener(v -> {
//            intent.setClass(this, UpStoreActivity.class);
//            intent.putExtra("title", "昵称");
//            startActivity(intent);
        });
        viewDataBinding.bindLayout.setOnClickListener(v -> {
//            intent.setClass(this, ThreeBindActivity.class);
//            startActivity(intent);
        });
    }

    public void popuShare() {
        List<String> data = new ArrayList<>();
        data.add("拍照");
        data.add("从相册选择");

        // 底部选择框
        new MenuDialog.Builder(this)
                .setList(data)
                .setListener(new MenuDialog.OnListener<String>() {

                    @Override
                    public void onSelected(BaseDialog dialog, int position, String string) {
                        switch (position) {
                            case 0:

                                PictureSelector.create(EditInformationActivity.this)
                                        .openCamera(PictureMimeType.ofImage())
                                        .loadImageEngine(GlideEngine.createGlideEngine())
                                        .forResult(new OnResultCallbackListener<LocalMedia>() {
                                            @Override
                                            public void onResult(List<LocalMedia> result) {
                                                Glide.with(EditInformationActivity.this)
                                                        .asBitmap()
                                                        .load(result.get(0).getPath())
                                                        .circleCrop()
                                                        .into(viewDataBinding.headImage);
                                                if (Build.VERSION.SDK_INT > 28) {
                                                    login(MyUtils.ysbitmao(result.get(0).getAndroidQToPath()));
                                                } else {
                                                    login(MyUtils.ysbitmao(result.get(0).getPath()));
                                                }
                                            }

                                            @Override
                                            public void onCancel() {

                                            }
                                        });


                                break;
                            case 1:

                                // 图片选择全部功能
                                PictureSelector.create(EditInformationActivity.this)
                                        .openGallery(PictureMimeType.ofImage())
                                        .loadImageEngine(GlideEngine.createGlideEngine()) // 请参考Demo GlideEngine.java
                                        .isWeChatStyle(true)// 是否开启微信图片选择风格
                                        .imageSpanCount(3)// 每行显示个数
                                        .maxSelectNum(1)// 最大图片选择数量
                                        .isCamera(false)
                                        .forResult(new OnResultCallbackListener<LocalMedia>() {
                                            @Override
                                            public void onResult(List<LocalMedia> result) {
                                                Glide.with(EditInformationActivity.this)
                                                        .asBitmap()
                                                        .load(result.get(0).getPath())
                                                        .circleCrop()
                                                        .into(viewDataBinding.headImage);
                                                if (Build.VERSION.SDK_INT > 28) {
                                                    login(MyUtils.ysbitmao(result.get(0).getAndroidQToPath()));
                                                } else {
                                                    login(MyUtils.ysbitmao(result.get(0).getPath()));
                                                }

                                            }

                                            @Override
                                            public void onCancel() {

                                            }
                                        });


                                break;
                            default:
                                break;
                        }
                    }

                    @Override
                    public void onCancel(BaseDialog dialog) {
                    }
                }).show();

    }


    @Override
    protected void onResume() {
        super.onResume();
        if (!DataHelputils.name.equals("0")) {
            viewDataBinding.nichengText.setText(DataHelputils.name);
            login(Hawk.get("head"));
        }
    }


    private void login(String url) {
        LoginPar par = new LoginPar();
        par.setPhone(viewDataBinding.phoneText.getText().toString());
        par.setAlias(viewDataBinding.nichengText.getText().toString());
        par.setPersonType(5);
        par.setHead(url);
        par.setRUserID(String.valueOf(HawkUtil.getUserId()));
        EasyHttp.post(HttpConfig.login)
                .cacheKey(HttpConfig.login)
                .upJson(GsonUtils.toJson(par))
                .execute(new SimpleCallBack<AppUser>() {
                    @Override
                    public void onSuccess(AppUser model) {
                        ToastUtils.showShort("修改成功");
                        if (HawkUtil.getUserId() != null) {
                            Hawk.delete(Constant.HAWK_USER_INFO);
                            Hawk.delete("ctype");
                            Hawk.delete("phone");
                            Hawk.delete("head");
                            Hawk.delete("alias");
                            Hawk.put("ctype", model.getCtype());
                            Hawk.put("phone", model.getPhone());
                            Hawk.put(Constant.HAWK_USER_INFO, model.getId());
                            Hawk.put("head", model.getHead());
                            Hawk.put("alias", model.getAlias());
                        } else {
                            Hawk.put("phone", model.getPhone());
                            Hawk.put("ctype", model.getCtype());
                            Hawk.put(Constant.HAWK_USER_INFO, model.getId());
                            Hawk.put("head", model.getHead());
                            Hawk.put("alias", model.getAlias());
                        }

                    }

                    @Override
                    public void onError(ApiException e) {

                    }

                    @Override
                    public void onCompleted() {
                    }
                });

    }

}
